package com.kd.juhaowan.ui;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.flyjingfish.shapeimageviewlib.ShapeImageView;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.GameDetailApi;
import com.kd.juhaowan.http.api.GameDownloadApi;
import com.kd.juhaowan.http.api.ReciveGiftApi;
import com.kd.juhaowan.http.model.GameModel;
import com.kd.juhaowan.http.model.GiftModel;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.ui.adapter.BaseRecyclerViewAdapter;
import com.kd.juhaowan.ui.adapter.BaseViewHolder;
import com.kd.juhaowan.ui.dialog.ConfirmDialog;
import com.kd.juhaowan.ui.holder.GameInfoImageViewHolder;
import com.kd.juhaowan.ui.holder.GiftViewHolder;
import com.kd.juhaowan.ui.listener.OnItemClickListener;
import com.kd.juhaowan.ui.listener.OnItemDianzanListener;
import com.kd.juhaowan.utils.DeviceUtil;
import com.kd.juhaowan.utils.GlideHelper;
import com.kd.juhaowan.utils.LogUtil;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.luck.picture.lib.entity.LocalMedia;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class GameDetailActivity extends BaseActivity implements OnItemClickListener, OnItemDianzanListener {


    @BindView(R.id.gamedetail_image)
    ShapeImageView videoView;
    @BindView(R.id.gamedetail_icon)
    ShapeImageView iconView;
    @BindView(R.id.gamedetail_name)
    TextView nameView;
    @BindView(R.id.gamedetail_cat)
    TextView cateView;
    @BindView(R.id.gamedetail_people)
    TextView peopleView;
    @BindView(R.id.gamedetail_gift_count)
    TextView giftCountView;
    @BindView(R.id.gamedetail_djq_count)
    TextView djqCountView;
    @BindView(R.id.gamedetail_zhekou_layout)
    LinearLayout zhekouLayout;
    @BindView(R.id.gamedetail_zhekou_text)
    TextView zhekouText;
    @BindView(R.id.gamelist_tag)
    LinearLayout tagListview;
    @BindView(R.id.gamedetail_star)
    TextView starView;
    @BindView(R.id.gamedetail_fuli)
    TextView fuliView;
    @BindView(R.id.login_confirm)
    TextView downloadView;
    @BindView(R.id.gamedetail_giftList)
    RecyclerView giftListView;
    @BindView(R.id.item_lingqu)
    TextView sixView;
    private BaseRecyclerViewAdapter<GiftViewHolder, GiftModel> giftAdapter;

    @BindView(R.id.gamedetail_imageList)
    RecyclerView imageListView;

    private GameModel model;
    private LinearLayout.LayoutParams params;
    String mSinglePath;
    private int singleTaskId;
    private BaseRecyclerViewAdapter<GameInfoImageViewHolder, LocalMedia> mAdapter;
    private ArrayList<LocalMedia> mediaList=new ArrayList<>();
    private ArrayList<LocalMedia> VedioList=new ArrayList<>();
    private String  gameid;
    private boolean defaultLoad;

    @Override
    protected void reInitDate() {
            initDate();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_account_login);
        params =new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.rightMargin= UIUtil.dip2px(GameDetailActivity.this,5);
        gameid =getIntent().getStringExtra("id");
        defaultLoad = getIntent().getBooleanExtra("startdownload",false);
        setAdapter();
       initDate();
    }

    private void initDate(){
        EasyHttp.post(this).api(new GameDetailApi(gameid)).request(new HttpCallbackProxy<HttpData<GameModel>>(this){
            @Override
            public void onHttpSuccess(HttpData<GameModel> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                model = result.getData();
                LocalMedia media1 = LocalMedia.generateHttpAsLocalMedia(model.getVideofiles());
                VedioList.add(media1);
                if(model.getImages()!=null){
                    for (String abc :model.getImages()) {
                        LocalMedia media = LocalMedia.generateHttpAsLocalMedia(abc);
                        mediaList.add(media);
                    }
                }
                setView();
                if(defaultLoad){
                    startDownload();
                }
            }
        });
    }
    private ConfirmDialog dialog = null;
    @OnClick(R.id.item_lingqu)
    public void onLingquClick(){
        GiftModel giftModel= model.getSix_package();
        if(giftModel!=null&&giftModel.getIs_receive()==0){
            EasyHttp.post(this).api(new ReciveGiftApi(giftModel.getId(),model.getId(), DeviceUtil.isInstallApp(GameDetailActivity.this,model.getGame_package_name())?1:2)).request(new HttpCallbackProxy<HttpData<GiftModel>>(this){
                @Override
                public void onHttpSuccess(HttpData<GiftModel> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    sixView.setText("已领取");
                    sixView.setBackgroundResource(R.drawable.gift_btn_recived);
                    if(!DeviceUtil.isInstallApp(GameDetailActivity.this,model.getGame_package_name())){

                       onLoginClick(null);
                    }


                    ConfirmDialog.Builder builder = new ConfirmDialog.Builder(GameDetailActivity.this);
                    builder.setMessage(result.getMessage());
                    builder.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();

                            if(DeviceUtil.isInstallApp(GameDetailActivity.this,model.getGame_package_name())){
                                final Intent intent = getPackageManager().getLaunchIntentForPackage(model.getGame_package_name());
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                                startActivity(intent);
                            }
                        }
                    });
                    dialog = builder.create();
                    dialog.show();

                }
            });
        }

    }

    private void setAdapter(){
        giftAdapter = new BaseRecyclerViewAdapter<GiftViewHolder, GiftModel>() {
            @NonNull
            @Override
            public GiftViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View view = inflater.inflate(R.layout.item_gamedetail_gift, null, false);
                GiftViewHolder holder=new GiftViewHolder(view);
                holder.setOnItemClickListener(getOnItemClickListener());
                return  holder;

            }

            @Override
            public void onBindViewHolder(@NonNull GiftViewHolder holder, int position) {
                holder.setDate(getItem(position));

            }
        };
        giftAdapter.setOnItemClickListener(this);
        giftAdapter.resetAdapterData(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);

        giftListView.setLayoutManager(layoutManager);
        giftListView.setAdapter(giftAdapter);


        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
        layoutManager2.setOrientation(RecyclerView.HORIZONTAL);
        imageListView.setLayoutManager(layoutManager2);

        mAdapter = new BaseRecyclerViewAdapter<GameInfoImageViewHolder, LocalMedia>() {
            @NonNull
            @Override
            public GameInfoImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View view = inflater.inflate(R.layout.item_gameinfo_image, parent, false);
                GameInfoImageViewHolder holder = new GameInfoImageViewHolder(view);
                holder.setOnItemClickListener(getOnItemClickListener());
                return holder;

            }

            @Override
            public void onBindViewHolder(@NonNull GameInfoImageViewHolder holder, int position) {
                holder.setDate(getItem(position).getAvailablePath());
            }
        };

        mAdapter.setOnItemClickListener(this);
        imageListView.setAdapter(mAdapter);

    }

    @Override
    public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int position) {
        if(viewHolder instanceof GameInfoImageViewHolder)
        {
            GlideHelper.imagePreview((Activity) GameDetailActivity.this,position,mediaList);

        }
    }

    @Override
    public void onItemDianzanClick(BaseViewHolder viewHolder, int position) {
        GiftModel model = giftAdapter.getItem(position);
        if(model.getIs_receive()==0){
            EasyHttp.post(this).api(new ReciveGiftApi(model.getId(),model.getGame_id(), DeviceUtil.isInstallApp(this,model.getGame_package_name())?1:2)).request(new HttpCallbackProxy<HttpData<GiftModel>>(this){
                @Override
                public void onHttpSuccess(HttpData<GiftModel> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    model.setIs_receive(1);
                    model.setCode(result.getData().getCode());
                    giftAdapter.notifyItemChanged(position,model);
                }
            });
        }else{
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            if(clipboard != null){
                ClipData clip = ClipData.newPlainText("text", model.getCode());
                clipboard.setPrimaryClip(clip);
                Toast.makeText(this,"已复制到剪贴板",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void startDownload(){
        BaseDownloadTask singleTask = FileDownloader.getImpl().create(model.getUrlfile())
//                .setPath(mSinglePath,false)
                .setPath(mSinglePath,false)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                //.setTag()
                .setListener(new FileDownloadSampleListener(){
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei","pending taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes);

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        downloadView.setText("下载中（"+(int)(soFarBytes*1.0/totalBytes*100)+"%）");
                        Log.d("feifei","progress taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes+",speed:"+task.getSpeed());
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        downloadView.setText("安装");
                        startVersionInstallTask(new File(mSinglePath));
                        Log.d("feifei","blockComplete taskId:"+task.getId()+",filePath:"+task.getPath()+",fileName:"+task.getFilename()+",speed:"+task.getSpeed()+",isReuse:"+task.reuse());
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Log.d("feifei","completed taskId:"+task.getId()+",isReuse:"+task.reuse());
                        downloadView.setText("安装");
                        startVersionInstallTask(new File(mSinglePath));
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei","paused taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes);
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.d("feifei","error taskId:"+task.getId()+",e:"+e.getLocalizedMessage());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Log.d("feifei","warn taskId:"+task.getId());
                    }
                });

        singleTaskId =  singleTask.start();

    }


    public void startVersionInstallTask(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        final Uri apkUri;

        if (file == null && !file.exists()) {
            LogUtil.debugLog("gamedetal", "startVersionInstallTask ========> file is not exists");
            return;
        }

        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String authority = getApplication().getPackageName() + ".PhotoPicker";
            apkUri = FileProvider.getUriForFile(getApplicationContext(), authority, file);
//            apkUri = Uri.fromFile(file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            apkUri = Uri.fromFile(file);
        }

        LogUtil.debugLog("gamedetal", "startVersionInstallTask ========> apkUri: " + apkUri.toString());

        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        startActivity(intent);
    }



    private void setView(){
//        model.setGame_package_name("com.hzhf.ajss.aj223");
        StringBuilder builder = new StringBuilder(model.getGame_package_name().trim());
//        builder.append(gameid);
        builder.append(".apk");
        File  file = new File(getExternalCacheDir(), builder.toString());
//        mSinglePath = FileDownloadUtils.getDefaultSaveRootPath()+
////                File.separator+"feifei_save"+
//                File.separator+model.getGame_package_name().trim()+".apk";;
        mSinglePath = file.getAbsolutePath();
        byte status =  FileDownloader.getImpl().getStatus(model.getUrlfile(),mSinglePath);
        LogUtil.debugLog(status+"status");

        GlideHelper.loadGoodsCover(Glide.with(iconView),iconView,model.getLogoimage());
//        GlideHelper.loadGoodsCover(Glide.with(videoView),videoView,model.getVideofiles());
        GlideHelper.loadGoodsCover(Glide.with(videoView),videoView,model.getFirst_frame_img());
        nameView.setText(model.getName());
        starView.setText(model.getScore());
        cateView.setText(model.getCat_name());
        peopleView.setText(model.getPeople_are_playing()+"人在玩");
        fuliView.setText(Html.fromHtml(model.getGame_benefits()));
        if(model.getDiscount()>0){
            zhekouLayout.setVisibility(View.VISIBLE);
            zhekouText.setText(model.getDiscount()+"折直充");
        }else{
            zhekouLayout.setVisibility(View.GONE);
        }
        if(DeviceUtil.isInstallApp(getApplicationContext(),model.getGame_package_name())){
            downloadView.setText("启动");
        }else{
            downloadView.setText("立即下载（"+model.getGame_package_size()+"）");
        }
        String[] tags =model.getTags();
        LogUtil.debugLog("dafa"+tags==null?"null":tags.length+"");
        if(tags!=null&&tags.length>0){
            tagListview.setVisibility(View.VISIBLE);
            tagListview.removeAllViews();
            for (String adb:tags) {
                TextView tv=new TextView(GameDetailActivity.this);
                tv.setGravity(Gravity.CENTER);
                tv.setBackgroundResource(R.drawable.tag_bg);
                tv.setPadding(UIUtil.dip2px(GameDetailActivity.this,5),0,UIUtil.dip2px(GameDetailActivity.this,5),0);
                tv.setText(adb);
                tv.setTextColor(getColor(R.color.login_edit_hint));
                tv.setTextSize(11);
                tagListview.addView(tv,params);
            }


//            searchHistoryAdapter.resetAdapterData(Arrays.asList(tags));
        }else {
            tagListview.setVisibility(View.GONE);
        }
        GiftModel giftModel= model.getSix_package();
        if(giftModel==null){
            sixView.setText("不可领");
            sixView.setBackgroundResource(R.drawable.gift_btn_recived);
        }else if (giftModel.getIs_receive()==1){
            sixView.setText("已领取");
            sixView.setBackgroundResource(R.drawable.gift_btn_recived);
        }else {
            sixView.setText("领取");
            sixView.setBackgroundResource(R.drawable.login_small_btn);
        }
        giftCountView.setText(model.getNumber_regular()+"");
        djqCountView.setText(model.getNumber_voucher()+"");
        giftAdapter.resetAdapterData(model.getListGiftpack());
        mAdapter.resetAdapterData(mediaList);
    }
    @OnClick(R.id.gamedetail_djq_layout)
    public void onDjqClick(){
        Intent in = new Intent(GameDetailActivity.this, GameDjqActivity.class);
        in.putExtra("game",model);
        startActivity(in);
    }
    @OnClick(R.id.gamedetail_gift_layout)
    public void ongiftClick(){
        Intent in = new Intent(GameDetailActivity.this, GameGiftActivity.class);
        in.putExtra("game",model);
        startActivity(in);
    }
    @OnClick(R.id.gamedetail_vedio)
    public void onVedioClick(){
        GlideHelper.imagePreview((Activity) GameDetailActivity.this,0,VedioList);
    }
    @OnClick(R.id.actvity_back)
    public void onBackClick(){
        finish();
    }


    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.activity_gamedetail;
    }

//    @OnClick(R.id.login_account_forget)
//    public void onForgetClick(View view){
//
//    }

    @OnClick(R.id.login_confirm)
    public void onLoginClick(View view){
        if(DeviceUtil.isInstallApp(getApplicationContext(),model.getGame_package_name())){
            final Intent intent = getApplication().getPackageManager().getLaunchIntentForPackage(model.getGame_package_name());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            startActivity(intent);

        }else {
            EasyHttp.post(this).api(new GameDownloadApi(gameid)).request(new HttpCallbackProxy<HttpData<GameModel>>(this){
                @Override
                public void onHttpSuccess(HttpData<GameModel> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    startDownload();
                }
            });


        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(singleTaskId!=0){
   FileDownloader.getImpl().pause(singleTaskId);

        }
//        FileDownloader.getImpl().pause(downloadId2);
    }
}
